package com.ruoyi.shop.goods.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.ruoyi.common.exception.ServiceException;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.shop.common.constant.ShopConstants;
import com.ruoyi.shop.common.core.domain.ShopCategory;
import com.ruoyi.shop.common.core.mapper.ShopCategoryMapper;
import com.ruoyi.shop.common.utils.ShopUtils;
import com.ruoyi.shop.goods.service.IShopGoodsCategoryService;

/**
 * shopCategoryService业务层处理
 *
 * @author ruoyi
 * @date 2022-02-17
 */
@Service
public class ShopGoodsCategoryServiceImpl implements IShopGoodsCategoryService {

    @Autowired
    private ShopCategoryMapper shopCategoryMapper;

    /**
     * 查询商品分类
     *
     * @param categoryId 商品分类主键
     * @return 商品分类
     */
    @Override
    public ShopCategory selectCategoryById(Long categoryId) {
        return shopCategoryMapper.selectCategoryById(categoryId);
    }

    /**
     * 查询商品分类
     *
     * @param parentId 商品分类父主键
     * @return 商品分类
     */
    @Override
    public List<ShopCategory> selectCategoryByParentId(Long parentId) {
        ShopCategory category = new ShopCategory();
        category.setParentId(parentId);
        category.setCategoryType(ShopConstants.SHOP_CATEGORY_TYPE_GOODS);// 商品分类
        return shopCategoryMapper.selectCategoryList(category);
    }

    /**
     * 查询商品分类列表
     *
     * @param category 商品分类
     * @return 商品分类
     */
    @Override
    public List<ShopCategory> selectCategoryList(ShopCategory category) {
        category.setCategoryType(ShopConstants.SHOP_CATEGORY_TYPE_GOODS);// 商品分类
        return shopCategoryMapper.selectCategoryList(category);
    }

    /**
     * 新增商品分类
     *
     * @param category 商品分类
     * @return 结果
     */
    @Override
    public int insertCategory(ShopCategory category) {
        if (category.getParentId().equals(Long.valueOf(0))) {
            category.setAncestors("0");
            category.setLevel(1);
        } else {
            ShopCategory info = shopCategoryMapper.selectCategoryById(category.getParentId());
            // 如果父节点不为"正常"状态,则不允许新增子节点
            if ( !UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
                throw new ServiceException("分类停用，不允许新增");
            }
            category.setAncestors(info.getAncestors() + "," + category.getParentId());
            category.setLevel(StringUtils.countMatches(category.getAncestors(), ",") + 1);
        }
        category.setCategoryType(ShopConstants.SHOP_CATEGORY_TYPE_GOODS);// 商品分类
        category.setCreateTime(DateUtils.getNowDate());
        return shopCategoryMapper.insertCategory(category);
    }

    /**
     * 修改商品分类
     *
     * @param category 商品分类
     * @return 结果
     */
    @Override
    public int updateCategory(ShopCategory category) {
        if (category.getParentId().equals(Long.valueOf(0))) {
            category.setAncestors("0");
            category.setLevel(1);
        } else {
            ShopCategory info = shopCategoryMapper.selectCategoryById(category.getParentId());
            category.setAncestors(info.getAncestors() + "," + category.getParentId());
            category.setLevel(StringUtils.countMatches(category.getAncestors(), ",") + 1);
        }
        category.setCategoryType(ShopConstants.SHOP_CATEGORY_TYPE_GOODS);// 商品分类
        category.setUpdateTime(DateUtils.getNowDate());
        return shopCategoryMapper.updateCategory(category);
    }

    /**
     * 批量商品分类
     *
     * @param categoryId 商品分类主键
     * @return 结果
     */
    @Override
    public int deleteCategoryById(Long categoryId) {
        return shopCategoryMapper.deleteCategoryById(categoryId);
    }

    /**
     * 根据父ID查询数量
     *
     * @param parentId 商品分类父主键
     * @return
     */
    @Override
    public int selectCategoryCount(Long parentId) {
        ShopCategory category = new ShopCategory();
        category.setParentId(parentId);
        return shopCategoryMapper.selectCategoryCount(category);
    }

    /**
     * 查询分类树（排除下级）
     *
     * @param category
     * @return
     */
    @Override
    public List<Ztree> selectCategoryTreeExcludeChild(ShopCategory category) {
        Long excludeId = category.getExcludeId();
        category.setCategoryType(ShopConstants.SHOP_CATEGORY_TYPE_GOODS);// 商品分类
        List<ShopCategory> categorys = shopCategoryMapper.selectCategoryList(category);
        if (excludeId.intValue() > 0) {
            categorys.removeIf(d -> d.getCategoryId().intValue() == excludeId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), excludeId + ""));
        }
        List<Ztree> ztrees = initZtree(categorys);
        return ztrees;
    }

    /**
     * 对象转分类树
     *
     * @param categoryList 分类列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<ShopCategory> categoryList) {
        List<Ztree> ztrees = new ArrayList<Ztree>();
        for (ShopCategory category : categoryList) {
            if (UserConstants.NORMAL.equals(category.getStatus())) {
                Ztree ztree = new Ztree();
                ztree.setId(category.getCategoryId());
                ztree.setpId(category.getParentId());
                ztree.setName(category.getCategoryName());
                ztree.setTitle(category.getCategoryName());
                ztrees.add(ztree);
            }
        }
        return ztrees;
    }

    /**
     * 获取所有可用的分类
     *
     * @return 获取所有分类及子类
     */
    @Override
    public List<ShopCategory> queryCategorys() {
        ShopCategory param = new ShopCategory();
        param.setStatus(UserConstants.NORMAL);// 状态可用
        param.setCategoryType(ShopConstants.SHOP_CATEGORY_TYPE_GOODS);// 商品分类
        List<ShopCategory> lists = shopCategoryMapper.selectCategoryList(param);
        lists.forEach(category -> category.setLogo(ShopUtils.getAbsoluteUrl(category.getLogo())));
        return getChildPerms(lists, 0);
    }

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list     分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<ShopCategory> getChildPerms(List<ShopCategory> list, int parentId) {
        List<ShopCategory> returnList = new ArrayList<ShopCategory>();
        for (Iterator<ShopCategory> iterator = list.iterator(); iterator.hasNext(); ) {
            ShopCategory t = (ShopCategory) iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId) {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list
     * @param t
     */
    private void recursionFn(List<ShopCategory> list, ShopCategory t) {
        // 得到子节点列表
        List<ShopCategory> childList = getChildList(list, t);
        t.setChildren(childList);
        for (ShopCategory tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<ShopCategory> getChildList(List<ShopCategory> list, ShopCategory t) {
        List<ShopCategory> tlist = new ArrayList<ShopCategory>();
        Iterator<ShopCategory> it = list.iterator();
        while (it.hasNext()) {
            ShopCategory n = (ShopCategory) it.next();
            if (n.getParentId().longValue() == t.getCategoryId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<ShopCategory> list, ShopCategory t) {
        return getChildList(list, t).size() > 0;
    }

}
